package org.pearl.oauth2.resourceserver001demo.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 *
 */

@Component
public class MyAuthenticationEntryPoint implements AuthenticationEntryPoint {


    private ObjectMapper objectMapper = new ObjectMapper();


    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response,
                         AuthenticationException authException) throws ServletException {
        try {
            authException.printStackTrace();
            // 1. 检查看服务端是否已将数据输出到客户端，如果已返回，则不处理
            if (response.isCommitted()) {
                return;
            }
            // 2. 封装结果信息，应该使用统一结果集封装，这里使用Map
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json;charset=utf-8");
            Map<String, Object> result = new HashMap<>();
            result.put("code", 401);
            result.put("msg", authException.getMessage());
            result.put("result", "认证失败");
            objectMapper.writeValue(response.getOutputStream(), result);
        } catch (Exception e) {
            throw new ServletException(e);
        }
    }
}